package kaalanshare;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: twin
 * Date: 23.04.12
 * Time: 17:35
 * To change this template use File | Settings | File Templates.
 */
public class NetFolderBuilder implements Runnable {
    public static HashMap<InetAddress, FolderStructure> map = new HashMap<InetAddress, FolderStructure>();

    @Override
    public void run() {
        byte[] buffer = new byte[65536];
        DatagramSocket serverSocket = null;

        try {
            serverSocket = new DatagramSocket(1991);
            serverSocket.setBroadcast(true);
        } catch (SocketException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        DatagramPacket recvPacket = new DatagramPacket(buffer, buffer.length);

        byte[] recvData;
        try {
            serverSocket.receive(recvPacket);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        recvData = recvPacket.getData();

        ByteArrayInputStream bis = new ByteArrayInputStream(recvData);
        ObjectInput in = null;
        try {
            in = new ObjectInputStream(bis);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        FolderStructure o = null;
        if (in != null) {
            try {
                o = (FolderStructure) in.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }

        try {
            bis.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        synchronized (NetFolderBuilder.class) {
            map.put(recvPacket.getAddress(), o);
        }

    }
}
